// Maps helpers.
var failed = false;
function geoLookup(loc, callback) {
  if (!geocoder) {
    if (!failed) {
      failed = true;
      alert('Game setup failed.  Try reloading page.');
    }
    return;
  }
  geocoder.getLatLng(loc, callback);
}

// JS helpers.
function el(e) {
  return document.getElementById(e);
}

function globalEval(script) {
  if (!script)
    return;
  if (window.execScript) {
    // On IE use this to exec script in global context
    return window.execScript(script);
  } else if (window.setTimeout) {
    return window.setTimeout(script, 0);
  } else if (window.eval) {
    return window.eval(script);
  } else {
    return eval(script);
  }
}

function log(output) {
  var evalOut = el('log');
  if (output == null) {
    output = 'null';
  } else if (typeof output == 'object') {
    try {
      output = '[object]  type=' + output.getType();
    } catch (e) {
      output = '[object]';
    }
  } else if (output == undefined) {
    output = 'undefined';
  } else {
    output = '' + output;
  }

  outText += '<div style="border-bottom:1px solid #f0f0f0;">' + 
      output.replace(/\n/g, '<br>\n') + '</div>';

  evalOut.innerHTML = outText + '<br><br>';
  evalOut.scrollTop = evalOut.scrollHeight;
}

function unescapeXml(xml) {
  return xml.
    replace(/&lt;/g,   '<').
    replace(/&gt;/g,   '>').
    replace(/&apos;/g, "'").
    replace(/&quot;/g, '"').
    replace(/&amp;/g,  '&');
}

// Geom
/* Keep an angle in [-180,180] */
function fixAngle(a) {
  while (a < -180) {
    a += 360;
  }
  while (a > 180) {
    a -= 360;
  }
  return a;
}

function clamp(val, min, max) {
  if (val < min) {
    return min;
  } else if (val > max) {
    return max;
  }
  return val;
}
